#include "plasticpresses.h"
#include "ui_plasticpresses.h"
#include "common.h"
#include <QDate>
#include <QTime>
#include <QJsonParseError>
#include <QJsonObject>
#include <QJsonDocument>
#include "Device/DeviceState/devicestate.h"
#include "../../DataBase/dbtab_plasticpresses.h"

#define TIMES    30
#define SHOW    0
bool PlasticPresses::QC_Scan_ckeck = false;
bool PlasticPresses::l_QC_Scan_ckeck = false;

bool PlasticPresses::Equipment_ckeck = false;
bool PlasticPresses::l_Equipment_ckeck = false;
bool PlasticPresses::_orderBegin = false;
int PlasticPresses::m_systemStatus;
PlasticPresses::PlasticPresses(MainWindow *parent) :
    MainWidget(parent),
    ui(new Ui::PlasticPresses),
    m_mainmenu(NULL),
    m_ContactUsSet(NULL),
    m_LogonRightsEdit(NULL),
    m_PlasticPressessInfo(NULL),
    m_ammeterDate(NULL),
    AlarmList({"模1温度超温","模2温度超温","","","","","","","","","","","","网络异常","等待刷卡","订单完成"}),
    m_circleTimer(new QTimer(0)),
    mEd(NULL),
    timeId(startTimer(200)),//per 200 ms
    heartId(startTimer(10000)),//per 10 seconds
    timeDelayId(startTimer(50)),
    mFlasbEnable(true),

    mCurrStr(""),
    mTextColor(Qt::green),
    mBackColor(Qt::white),
    /*----zhanglong*/
    m_freshLEDTimer(new QTimer(0)),
    mFlash(0),
    /*----zhanglong*/
    Alarm_Count(0),
    TeAlarm_Count(0),
    l_systemStatus(0),
    m_mitsubishi(NULL),
    mWgtChanged(PLASTIC_MAIN_WGT),
    m_DelayTimeSet1Para({"","","","","",""}),
    m_DelayTimeSet2Para({"","","","","",""}),
    m_plcStatus(false),
    m_register_flag(false),
    m_tcpSocket(NULL),
    tProctionInfo({"","","","","","","","","","","",""}),
    m_currentCount_temp(""),
    m_currentWorkStatus_temp(""),
    m_currentSetValue_temp(""),
    m_currentRealValue_temp(""),
    m_dumpEnergy_temp(""),
    m_currentCountUpdate_timer(NULL),
    m_post_once_flag(false),
    _iNum(0),
    m_task_timeId(startTimer(500)),
    m_orderFinish_flag(false),
    _objToserver(QJsonObject())

{
    ui->setupUi(this);
    setOrderButtonHidden();
    initHttpClient();
    initHttpServer();
    initUi();
    initButtonSlot();
    initFont();
    initText();
    /*----zhanglong*/
    initLEDcycleTime();
    initAmmeterScaleModbusSlave();
    initFlash();
    initMitsubishiPlcFun();
    initScaleSerialSetting();
    initSpotDelayTime();
    initQCScanCheck();
    initOrderRecordShow();
    this->setFocus();
#if 0
    initSocketTest();
#endif

#ifndef SHOW
    ui->pushButton->hide();
#endif
    //firstCheck
    connect(ui->btn_FirstCheck,    SIGNAL(clicked(bool)),                  this,                       SLOT(firstProductionOK_toScanOperator()));
    connect(ui->btn_FirstCheck,    SIGNAL(clicked(bool)),                  this,                       SLOT(firstProductionOK_toScanOperator2()));
    //qc
    connect(ui->btn_QCCheck,       SIGNAL(clicked(bool)),                  this,                       SLOT(firstQcCheck2()));
    connect(ui->btn_QCCheck,       SIGNAL(clicked(bool)),                  this,                       SLOT(firstQcCheck()));
    connect(ui->qc_scan_check,     SIGNAL(clicked(bool)),                  this,                       SLOT(QCCheckManualExecute()));
    ui->le_workorder->setVisible(false);
    ui->le_workorder_num->setVisible(false);
    ui->btn_order->setVisible(false);
    ui->btn_orderCompleted->setDisabled(true);
    ui->le_defectiveNumber->setEnabled(false);
    while(_workArr_pla.isEmpty() == false)
        _workArr_pla.removeFirst();

    connect(this,SIGNAL(showAmmeterData(QString)),this,  SLOT(slot_HaoDian(QString)) ); //耗电量
    connect(this,SIGNAL(showTemperatureData(QString)),this,  SLOT(slot_Module_1_temp(QString))); //模1温度
    connect(this,SIGNAL(showTemperature_OfModule2(QString)),this,   SLOT(slot_Module_2_temp(QString))); //模2温度
    connect(this,SIGNAL(sendScaleWeight(QString)),this,    SLOT(slot_chengZhong_weight(QString))); //称重重量
    connect(this,SIGNAL(sendScaleCount(QString)),this,     SLOT(slot_chengZhong_count(QString)));//称重计数

    _timerSendToserver = new QTimer(this);
    _timerSendToserver->setSingleShot(true);
    connect( _timerSendToserver, &QTimer::timeout, [=](){
        sendOperatorAndMaterial();
    });
}

void PlasticPresses::initSpotDelayTime()
{
    QTimer::singleShot(60000*60,this,SLOT(spotCheckTimerTips()));
}

void PlasticPresses::on_btn_SpotCheck_clicked()
{
    ui->btn_SpotCheck->setDisabled(true);
    m_systemStatus |= 0x4000;
    Equipment_ckeck = true;
    initSpotCheckEquipmentDialog();
}

void PlasticPresses::sendOperatorAndMaterial()
{

    m_httpClient->posOperator( m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,  _objToserver.value("Operator").toObject() , DeviceState::OPERATOR_WORK_STATION );

    for( int i =0; i < _jsArrToserver.size(); ++i)
    {
        m_httpClient->posMaterial( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  _jsArrToserver.at(i).toObject() );
    }
    _objToserver = QJsonObject();
    while( _jsArrToserver.size() > 0)
    {
        _jsArrToserver.removeFirst();
    }
}
void PlasticPresses::QCCheckManualExecute()
{
    ui->qc_scan_check->setDisabled(true);
    m_systemStatus |= 0x4000;
    QC_Scan_ckeck = true;
    initQCCheckDialog();
}

void PlasticPresses::initQCScanCheck()
{
    m_qc_checkDelayTimer->start(60000*120); //120 minute
    connect(m_qc_checkDelayTimer,SIGNAL(timeout()),this,SLOT(QCCheckTimerTips()));
}
void PlasticPresses::postWarnData(QString alarm, QString createtime)
{
    QJsonObject obj;
    obj.insert("alarm", alarm );
    obj.insert("createTime", createtime );
    m_httpClient->postWarningInfo( m_deviceInfo->deviceType,
                                   m_deviceInfo->deviceId,
                                   mParent->_productionVariant.TaskId,  obj );
}
void PlasticPresses::QCCheckTimerTips()
{
    if(!_orderBegin)
    {
        return;
    }
    QC_Scan_ckeck = true;
    m_systemStatus |= 0x4000;
    ui->qc_scan_check->setEnabled(true);
}


void PlasticPresses::on_btn_QCCheck_clicked()
{

}

void PlasticPresses::firstProductionOK_toScanOperator2()
{
    ui->btn_FirstCheck->setDisabled(true);
}

void PlasticPresses::firstQcCheck2()
{
    ui->btn_QCCheck->setDisabled(true);
}

void PlasticPresses::slot_sendOperator(QString strUserName, QString strUserId, DeviceState::DeviceStion  dd)
{
    QJsonObject obj;
    obj.insert("Operator", strUserName );
    obj.insert("OperatorId", strUserId );
    obj.insert("createtime", QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
    _objToserver.insert("Operator", obj);
    m_httpClient->posOperator( m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,  obj , dd);
}

void PlasticPresses::slot_sendMaterial(QString strCount, QString strMname, QString strMcode)
{
    QJsonObject obj;
    obj.insert("count", strCount );
    obj.insert("mname", strMname );
    obj.insert("mcode", strMcode );
    _jsArrToserver.append(obj);
}

void PlasticPresses::slot_sendGongZhang(QString strToolName,  QString strToolCode)
{
    QJsonObject obj;
    obj.insert("ToolingCode", strToolCode );
    obj.insert("ToolingName", strToolName );
    m_httpClient->posGongzhuang(m_deviceInfo->deviceType,
                                m_deviceInfo->deviceId,
                                mParent->_productionVariant.TaskId,
                                obj );
}


void PlasticPresses::slot_HaoDian( QString str)
{
    if( str.contains("KVA"))
    {
        str = str.remove("KVA").trimmed();
    }
    _DatasObj["耗电量"] = str;
}

void PlasticPresses::slot_Module_1_temp(QString str)
{
    _DatasObj["模1温度"] = str;

}

void PlasticPresses::slot_Module_2_temp(QString str)
{
    _DatasObj["模2温度"] = str;
}

void PlasticPresses::slot_chengZhong_weight(QString str)
{
    _DatasObj["称重重量"] = str;
}

void PlasticPresses::slot_chengZhong_count(QString str)
{
    _DatasObj["称重计数"] = str;
}

void PlasticPresses::slot_Delay1(DelayTimeSet1Para d)
{
    _DatasObj["低压排气次数"] =    d.LowPressureCount;
    _DatasObj["高压排气次数"] =    d.HighPressureCount;
    _DatasObj["低压保压延时"] =    d.LowProtectTime;
    _DatasObj["高压保压延时"] =    d.HighProtectDelayTime;
    _DatasObj["泄压延时"] =    d.PressureReliefDelayTime;
    _DatasObj["低压排气延时"] =    d.LowPressureDelayTime;
}

void PlasticPresses::slot_Delay2(DelayTimeSet2Para d)
{
    _DatasObj["泄压延时2时间"] =    d.PressureReliefDelayTime2;
    _DatasObj["高压排气延时"] =    d.HighPaiQiDelayTime;
    _DatasObj["成型保压延时"] =    d.ChengxingBaoyaDelayTime;
    _DatasObj["顶出延时时间"] =    d.DingchuDelayTime;
    _DatasObj["泄压延时时间"] =    d.PressureReliefDelayTime;
    _DatasObj["握手信号"] =       d.HandshakeSignal;
}


void PlasticPresses::receiveStation_fromHttp(QString station)
{
    m_currentStation = station;
}



PlasticPresses::~PlasticPresses()
{
    deleteFun();
}

void PlasticPresses::initOrderRecordShow()
{
    ProductionVariant productinfo;
    queryCurrentOrder(productinfo,"");
    if (!productinfo.TaskId.isEmpty() && !productinfo.ProductName.isEmpty() && !productinfo.WorkNum.isEmpty() )
    {
        showProductionOrder();
    }
}


void PlasticPresses::getCurrentWgtIndex()
{
    if(ui->stackedWidget->currentWidget() == ui->page_plasticpress)
    {
        mWgtChanged = PLASTIC_MAIN_WGT;
        emit sendCurrentWgtIndex(mWgtChanged);
    }
    else if(ui->stackedWidget->currentWidget() == ui->page_mainmenu)
    {
        mWgtChanged = MAIN_MENU_WGT;
        emit sendCurrentWgtIndex(mWgtChanged);
    }
}

void PlasticPresses::initUi()
{
    ui->stackedWidget->setCurrentWidget(ui->page_plasticpress);
}


void PlasticPresses::spotCheckTimerTips()
{
    m_systemStatus |= 0x4000;
    Equipment_ckeck = true;
    ui->btn_SpotCheck->setEnabled(true);
}

void PlasticPresses::initLEDcycleTime()
{
    /*LED cnotrol time--zhanglong*/
    m_freshLEDTimer->start(800);
    connect(m_freshLEDTimer,   SIGNAL(timeout()),    this,   SLOT(LEDFrashCircleTimeSlot()));
}

void PlasticPresses::initFont()
{
    {
        QFont f("DejaVu Sans",20);
        ui->lab_warn->setFont(f);
        ui->btn_warn_clear->setFont(f);
    }
    {
        QFont f("DejaVu Sans",18);
        ui->lineEdit->setFont(f);
        ui->lineEdit_6->setFont(f);
        ui->lineEdit_13->setFont(f);
    }
    {
        QFont f("DejaVu Sans",20);
        ui->le_workorder->setFont(f);
        ui->le_workorder_num->setFont(f);
        ui->lineEdit_2->setFont(f);
        ui->le_workstatus->setFont(f);
        ui->lineEdit_4->setFont(f);
        ui->lineEdit_5->setFont(f);
        ui->lineEdit_7->setFont(f);
        ui->lineEdit_8->setFont(f);
        ui->le_settime->setFont(f);
        ui->le_realtime->setFont(f);
        ui->lineEdit_11->setFont(f);
        ui->lineEdit_12->setFont(f);
        ui->lineEdit_14->setFont(f);
        ui->lineEdit_15->setFont(f);
        ui->le_objCount->setFont(f);
        ui->le_obj_preCount->setFont(f);
        ui->btn_clearCount->setFont(f);
    }
}

void PlasticPresses::initText()
{
    ui->le_workorder->setText("工单号:");
    ui->le_workorder_num->setText("");
}

void PlasticPresses::initButtonSlot()
{
    connect(ui->btn_mainnenu,       SIGNAL(clicked(bool)),              this,                       SLOT(showMainMenu()));
    connect(ui->btn_contact,        SIGNAL(clicked(bool)),              this,                       SLOT(showContactUsSetting()));
    connect(ui->btn_login,          SIGNAL(clicked(bool)),              this,                       SLOT(showLogonRightsEditSetting()));
    connect(ui->btn_close,          SIGNAL(longclicked()),              this,                       SLOT(powerOff()));
    connect(ui->btn_sysInfo,        SIGNAL(clicked(bool)),              this,                       SLOT(showSysInfo()));
    connect(ui->btn_order,          SIGNAL(clicked(bool)),              this,                       SLOT(showProductionOrder()));
    connect(this,SIGNAL(sendProductionVariant(ProductionVariant)),      this,                       SLOT(receiveProductionVariant_Main(ProductionVariant)));
    connect(ui->btn_orderCompleted,     SIGNAL(clicked(bool)),          this,                       SLOT(orderCompleted_slots()));
}

void PlasticPresses::deviceCircleSend()
{
    m_circleTimer->start(10000);
    connect(m_circleTimer,   SIGNAL(timeout()),    this,   SLOT(deviceCircleTimeSlot()));
}

void PlasticPresses::initAmmeterScaleModbusSlave()
{
    m_ammeterDate = new AmmeterScale("/dev/"+m_usbPortName.port1_name,"9600","8","none","1");
    /*start for green----zhanglong*/
    m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","09 00",false);
    connect(m_ammeterDate,   SIGNAL(sendAmmeterPowerData(float)),    this,   SLOT(readAmmeterPowerData(float)));
    connect(m_ammeterDate,   SIGNAL(sendTemperature(int)),    this,   SLOT(readTemperature(int)));
    connect(m_ammeterDate,   SIGNAL(sendModule2Temperature(int)),    this,   SLOT(readTemperature_OfModule2(int)));
}

void PlasticPresses::showMainMenu()
{
    ui->stackedWidget->setCurrentWidget(ui->page_mainmenu);
    getCurrentWgtIndex();
    if( m_mainmenu == NULL)
        m_mainmenu = new MainMenu( ui->frame_mainmenu->layout(),ui->frame_mainmenu->width(),ui->frame_mainmenu->height(),ui->frame_mainmenu);
    connect(m_mainmenu, SIGNAL(exitCurr()),                                                         this,           SLOT(receiveExitMainMenu_Slot()));
    connect(m_mainmenu, SIGNAL(sendCurrentSubWgtIndex(WgtChanged)),                                 this,           SLOT(updateReceiSubWgtIndex(WgtChanged)));

    //目标1 - 低压排气
    connect(m_mainmenu, SIGNAL(receiveLowPressEnable_OfMainMenu()),                                 this,           SLOT(receiveLowPressEnable_OfMainwgt()));
    //目标1 - 低压排气
    connect(m_mainmenu, SIGNAL(receiveLowPressDisable_OfMainMenu()),                                this,           SLOT(receiveLowPressDisable_OfMainwgt()));
    //目标1 - 补压
    connect(m_mainmenu, SIGNAL(receiveAftercompactionEnable_OfMainMenu()),                          this,           SLOT(receiveAftercompactionEnable_OfMainwgt()));
    //目标1 - 补压
    connect(m_mainmenu, SIGNAL(receiveAftercompactionDisable_OfMainMenu()),                         this,           SLOT(receiveAftercompactionDisable_OfMainwgt()));

    connect(m_mainmenu, SIGNAL(receiveChouXinGangMode_FromMenu(bool)),                              this,           SIGNAL(writeChouXinGangFlag(bool)));
    connect(m_mainmenu, SIGNAL(receiveMotorMode_OfMenu(bool)),                                      this,           SIGNAL(writeMotorModeFlag(bool)));
    connect(m_mainmenu, SIGNAL(receiveGaoYaPaiQiMode_OfMenu(bool)),                                 this,           SIGNAL(writeGaoYaPaiQiFlag(bool)));
    connect(m_mainmenu, SIGNAL(receiveLowPressureCount_OfMainMenu(QString,QString)),                this,           SLOT(receiveLowPressureCount_OfMainwgt(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveHighPressureCount_OfMainMenu(QString,QString)),               this,           SLOT(receiveHighPressureCount_OfMainwgt(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveLowProtectDelaytime_OfMainMenu(QString,QString)),             this,           SLOT(receiveLowProtectDelaytime_OfMainwgt(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveReliefPressureDelaytime_OfMainMenu(QString,QString)),         this,           SLOT(receiveReliefPressureDelaytime_OfMainwgt(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveLowPreesurePaiqiDelaytime_OfMainMenu(QString,QString)),       this,           SLOT(receiveLowPressurePaiqiDelaytime_OfMainwgt(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveHighPreesureBaoyaDelaytime_OfMainMenu(QString,QString)),      this,           SLOT(receiveHighPressureBaoyaDelaytime_OfMainwgt(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveReliefPressureDelaytime2_OfMainMenu2(QString,QString)),       this,           SLOT(receiveReliefPressureDelaytime2_OfMainwgt2(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveHighPressurePaiqiDelaytime_OfMainMenu2(QString,QString)),     this,           SLOT(receiveHighPressurePaiqiDelaytime_OfMainwgt2(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveMoldingBaoyaDelaytime_OfMainMenu2(QString,QString)),          this,           SLOT(receiveMoldingBaoyaDelaytime_OfMainwgt2(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveTopoutDelaytime_OfMainMenu2(QString,QString)),                this,           SLOT(receiveTopoutDelaytime_OfMainwgt2(QString,QString)));
    connect(m_mainmenu, SIGNAL(receiveReliefPressureDelaytime_OfMainMenu2(QString,QString)),        this,           SLOT(receiveReliefPressureDelaytime_OfMainwgt2(QString,QString)));
    connect(this,       SIGNAL(sendProcessInfo(QString)),                                           m_mainmenu,     SLOT(receiveProcessInfo(QString)));
    connect(this,       SIGNAL(sendInputStatusInfo(QString)),                                       m_mainmenu,     SIGNAL(sendInputStatusInfo_fromPlastic(QString)));
    connect(this,       SIGNAL(sendOutputStatusInfo(QString)),                                      m_mainmenu,     SLOT(receiveOutputStatusInfo(QString)));

    //目标2
    connect(this,       SIGNAL(sendDelay1Info(DelayTimeSet1Para)),                                  m_mainmenu,     SLOT(receiveDelay1Info(DelayTimeSet1Para)));
    connect(this,       SIGNAL(sendDelay1Info(DelayTimeSet1Para)),                                  this,           SLOT(slot_Delay1(DelayTimeSet1Para)));
    //目标3
    connect(this,       SIGNAL(sendDelay2Info(DelayTimeSet2Para)),                                  m_mainmenu,     SLOT(receiveDelay2Info(DelayTimeSet2Para)));
    connect(this,       SIGNAL(sendDelay2Info(DelayTimeSet2Para)),                                  this,            SLOT(slot_Delay2(DelayTimeSet2Para)));
    connect( this, SIGNAL(closeInputDialog_ByHeadMan()), m_mainmenu, SIGNAL(closeInputDialog_ByHeadMan()) );
    connect( this, SIGNAL(closeSenconConfirmDialog_ByQcMan()), m_mainmenu, SIGNAL(closeSenconConfirmDialog_ByQcMan()) );
    m_mainmenu->show();
}

void PlasticPresses::showContactUsSetting()
{
    ui->stackedWidget->setCurrentWidget(ui->page_contactus);
    if( m_ContactUsSet == NULL)
        m_ContactUsSet = new ContactUsSet(ui->frame_contactus->layout(),ui->frame_contactus->width(),ui->frame_contactus->height(),ui->frame_contactus);
    connect(m_ContactUsSet,SIGNAL(exitCurr()),this,SLOT(receiveExitContact_Slot()));
    m_ContactUsSet->show();
}

void PlasticPresses::showLogonRightsEditSetting()
{
    ui->stackedWidget->setCurrentWidget(ui->page_logon_rights);
    if( m_LogonRightsEdit == NULL)
        m_LogonRightsEdit = new LogonRightsEdit(ui->frame_logon->layout(),ui->frame_logon->width(),ui->frame_logon->height(),ui->frame_logon);
    connect(m_LogonRightsEdit,SIGNAL(exitCurr()),this,SLOT(receiveExitContact_Slot()));
    m_LogonRightsEdit->show();
}

void PlasticPresses::receiveExitContact_Slot()
{
    ui->stackedWidget->setCurrentWidget(ui->page_plasticpress);
}

void PlasticPresses::receiveExitMainMenu_Slot()
{
    ui->stackedWidget->setCurrentWidget(ui->page_plasticpress);
    getCurrentWgtIndex();
}

void PlasticPresses::showSysInfo()
{
    ui->stackedWidget->setCurrentWidget(ui->page_plasticpressinfo);
    if( NULL == m_PlasticPressessInfo )
        m_PlasticPressessInfo = new PlasticPressessInfo( ui->frame_plasticpressinfo->layout(),ui->frame_plasticpressinfo->width(),ui->frame_plasticpressinfo->height(),ui->frame_plasticpressinfo);
    connect(m_PlasticPressessInfo,SIGNAL(exitcurr()),this,SLOT(receiveExitContact_Slot()));

    connect(this,SIGNAL(sendIpStatus_OfMainWgt(bool)),m_PlasticPressessInfo,SLOT(showIpCommunicataStatus(bool)));  //与下位机通信
    connect(this,SIGNAL(plcConnnectedStatus_signals(bool)),m_PlasticPressessInfo,SLOT(showPlcCommunicataStatus(bool))); //与上位机通讯
    connect(this,SIGNAL(showAmmeterData(QString)),m_PlasticPressessInfo,SLOT(receiveAmmeterData(QString))); //耗电量
    connect(this,SIGNAL(showTemperatureData(QString)),m_PlasticPressessInfo,SLOT(receiveTemperatureData(QString))); //模1温度
    connect(this,SIGNAL(showTemperature_OfModule2(QString)),m_PlasticPressessInfo,SLOT(receiveTemperature_OfModule2(QString))); //模2温度
    connect(this,SIGNAL(sendScaleWeight(QString)),m_PlasticPressessInfo,SLOT(receiveScaleWeight_FromPlastic(QString))); //称重重量
    connect(this,SIGNAL(sendScaleCount(QString)),m_PlasticPressessInfo,SLOT(receiveScaleCount_FromPlastic(QString)));//称重计数
    m_PlasticPressessInfo->show();
}

void PlasticPresses::readAmmeterPowerData(float ammeter)
{
    QString dump_Energy = QString::number(ammeter) + " KVA";
    mCurrentWorkStatus.dumpEnergy = dump_Energy;
    if(m_post_once_flag)
    {
        putDetailFun("5");
    }
    emit showAmmeterData(dump_Energy);
}

void PlasticPresses::readTemperature(int temperatureData)
{
    /*----zhanglong*/
    if(temperatureData > 185)
    {
        TeAlarm_Count ++;
        if(TeAlarm_Count > 9)
        {
            TeAlarm_Count = 10;
            m_systemStatus |= 0x0001;
        }
    }
    else
    {
        if(TeAlarm_Count != 0)
        {
            TeAlarm_Count --;
        }
        else
        {
            m_systemStatus &= 0xfffe;
        }
    }
    QString temp_ture = QString::number(temperatureData) + " C";
    mCurrentWorkStatus.temperature = temp_ture;
    if(m_post_once_flag)
    {
        //        putDetailFun("5"); //TODO 20180717 NEED FINISH
    }
    emit showTemperatureData(temp_ture);
}

void PlasticPresses::readTemperature_OfModule2(int temperatureData)
{
    /*----zhanglong*/
    if(temperatureData > 185)
    {
        Alarm_Count ++;
        if(Alarm_Count > 9)
        {
            Alarm_Count = 10;
            m_systemStatus |= 0x0002;
        }
    }
    else
    {
        if(Alarm_Count != 0)
        {
            Alarm_Count --;
        }
        else
        {
            m_systemStatus &= 0xfffd;
        }
    }
    QString temp_ture = QString::number(temperatureData) + " C";
    mCurrentWorkStatus.temperature_OfModule2 = temp_ture;
    if(m_post_once_flag)
    {
        //        putDetailFun("5"); //TODO 20180717 NEED FINISH
    }
    emit showTemperature_OfModule2(temp_ture);
}

void PlasticPresses::updateReceiSubWgtIndex(WgtChanged wgt)
{
    mWgtChanged = wgt;
    emit sendCurrentWgtIndex(wgt);
}

void PlasticPresses::receiveLowPressEnable_OfMainwgt()
{
    _DatasObj["低压排气"] = QString("1");
    emit writeLowPressFlag(true);
}

void PlasticPresses::receiveLowPressDisable_OfMainwgt()
{
    _DatasObj["低压排气"] = QString("0");
    emit writeLowPressFlag(false);
}

void PlasticPresses::receiveAftercompactionEnable_OfMainwgt()
{
    _DatasObj["补压"] = QString("1");
    emit writeAftercompactionFlag(true);
}

void PlasticPresses::receiveAftercompactionDisable_OfMainwgt()
{
    _DatasObj["补压"] = QString("0");
    emit writeAftercompactionFlag(false);
}

void PlasticPresses::receiveLowPressureCount_OfMainwgt(QString value, QString bytesCount)
{
    emit writeLowPressureCount(value,bytesCount);
}

void PlasticPresses::receiveHighPressureCount_OfMainwgt(QString value, QString bytesCount)
{
    emit writeHighPressureCount(value,bytesCount);
}

void PlasticPresses::receiveLowProtectDelaytime_OfMainwgt(QString value, QString bytesCount)
{
    emit writeLowProtectDelaytime(value,bytesCount);
}

void PlasticPresses::receiveReliefPressureDelaytime_OfMainwgt(QString value, QString bytesCount)
{
    emit writeReliefPressureDelaytime(value,bytesCount);
}

void PlasticPresses::receiveLowPressurePaiqiDelaytime_OfMainwgt(QString value, QString bytesCount)
{
    emit writeLowPressurePaiqiDelaytime(value,bytesCount);
}

void PlasticPresses::receiveHighPressureBaoyaDelaytime_OfMainwgt(QString value, QString bytesCount)
{
    emit writeHighPressureBaoyaDelaytime(value,bytesCount);
}

void PlasticPresses::receiveReliefPressureDelaytime2_OfMainwgt2(QString value, QString bytesCount)
{
    emit writeReliefPressureDelaytime2_2(value,bytesCount);
}

void PlasticPresses::receiveHighPressurePaiqiDelaytime_OfMainwgt2(QString value, QString bytesCount)
{
    emit writeHighPressurePaiqiDelaytime_2(value,bytesCount);
}

void PlasticPresses::receiveMoldingBaoyaDelaytime_OfMainwgt2(QString value, QString bytesCount)
{
    emit writeMoldingBaoyaDelaytime_2(value,bytesCount);
}

void PlasticPresses::receiveTopoutDelaytime_OfMainwgt2(QString value, QString bytesCount)
{
    emit writeTopoutDelaytime_2(value,bytesCount);
}

void PlasticPresses::receiveReliefPressureDelaytime_OfMainwgt2(QString value, QString bytesCount)
{
    emit writeReliefPressureDelaytime_2(value,bytesCount);
}

void PlasticPresses::powerOff()
{
    TSystem2("poweroff");
}

void PlasticPresses::receiveipStatus_slots(bool status)
{
    emit sendIpStatus_OfMainWgt(status);
}

void PlasticPresses::writeDataToTcpServer()
{
    m_tcpSocket->getobj()->writeData();
}

void PlasticPresses::updateCurrentCount()
{
    if( m_currentCountUpdate_timer == NULL)
        m_currentCountUpdate_timer = new QTimer(this);
    m_currentCountUpdate_timer->start(1000);
    connect(m_currentCountUpdate_timer,   SIGNAL(timeout()),    this,   SLOT(updateCurrentCountCirle()));
}

void PlasticPresses::updateCurrentCountCirle()
{
    if(m_currentCount_temp.compare(mCurrentWorkStatus.objCount)!=0)
    {
        m_currentCount_temp = mCurrentWorkStatus.objCount;
        m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount",mCurrentWorkStatus.objCount);
    }
}

void PlasticPresses::startFirstProduction_slots()
{
    m_orderFinish_flag = false;
    _orderBegin = true;
    startTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
    sendUpdateTodayTask(); //订单开始只抛5号数据
    _timerSendToserver->start(3000);
    ui->btn_FirstCheck->setEnabled(true);
    ui->btn_QCCheck->setEnabled(true);
}

void PlasticPresses::spotCheckManualExecute()
{
    //TODO
}

void PlasticPresses::recordScaleData_slots()
{
    //    if ( mStandardPara->scaleWeight.toFloat()*1000 <=0)
    //    {
    //        MyMessageDialog::message(this,"警告","请检查电子秤是否设置关闭零点跟踪！");
    //    }

    //    DataBaseQuery query(DataBase::getDataBase());
    //    DataBase::getDataBase().open();
    //    DataBase::getDataBase().transaction();
    //    QMap<QString,QVariant> map_Save;
    //    map_Save.insert(DBTab_PlasticPresses::_TAB_PUNCHINGMACHINE_SCALE_WEIGHT,QVariant(mStandardPara->scaleWeight.toFloat()));
    //    map_Save.insert(DBTab_PlasticPresses::_TAB_PUNCHINGMACHINE_SCALE_COUNT,QVariant( ui->le_PScaleCount->text().toInt()));
    //    map_Save.insert(DBTab_PlasticPresses::_TAB_PLASTICPRESSES_TASK_ID, QVariant(m_current_taskId));
    //    map_Save.insert(DBTab_PlasticPresses::_ADD_TIME, QVariant(QDateTime::currentDateTime()));
    //    query.insert(DBTab_PlasticPresses::TAB_PLASTICPRESSES,  map_Save);

    //    DataBase::getDataBase().commit();
    //    DataBase::getDataBase().close();
    //    DataBase::getDataBase().open();
    //    DataBase::getDataBase().transaction();
    //    QString str;
    //    str = "SELECT "
    //        " SUM(" + DBTab_PlasticPresses::TAB_PUNCHINGMACHINE + "." + DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_SCALE_WEIGHT + "),"\
    //        " SUM(" + DBTab_PlasticPresses::TAB_PUNCHINGMACHINE + "." + DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_SCALE_COUNT + ")"\
    //        " FROM "  + DBTab_PlasticPresses::TAB_PUNCHINGMACHINE +\
    //        " WHERE " + DBTab_PlasticPresses::TAB_PUNCHINGMACHINE + "." + DBTab_PunchingMachine::_TAB_PUNCHINGMACHINE_TASK_ID + " = " + "\""+ m_current_taskId + "\"";

    //    query.execQString(str);
    //    if (query.next()) {
    //        m_current_order_finished_weight = query.value(0).toFloat();
    //        m_current_order_finished_count = query.value(1).toInt();
    //        mStandardPara->totalCount_FromScale = QString::number(m_current_order_finished_count);
    //    }
    //    ui->le_calibratedCount->setText(mStandardPara->calibrationCount);
    //    putDetailFun("22");//Put the scale total Count;
    //    DataBase::getDataBase().commit();
    //    DataBase::getDataBase().close();
    //    MyMessageDialog::message(0,"提示！","当前称重存储本地数据库成功！",1500);

}

void PlasticPresses::parseWorkStatus(QString warnstring)
{
    QByteArray warnarr = QByteArray::fromHex(warnstring.toLatin1());
    QByteArray arr_info = warnarr.remove(0,1).remove(warnarr.length()-3,3);
    QStringList list;
    list.clear();
    for(int i=0;i<arr_info.length(); i+=4)
    {
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);
    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            mCurrentWorkStatus.start = QString(temp_arr);
        }
        if(i == 1 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            Q_UNUSED(temp_arr);
        }
        if(i == 2)
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            QString str_temp = QString("%1").arg(value/10,10,'f',1);
            mCurrentWorkStatus.currSetValue = str_temp;
            if(m_post_once_flag)
            {
                putDetailFun("2");
            }
        }
        if(i == 3 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            Q_UNUSED(temp_arr);
        }
        if(i == 4 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            QString str_temp = QString("%1").arg(value/10,10,'f',1);
            mCurrentWorkStatus.currRealvalue = str_temp;
            if(m_post_once_flag)
            {
                putDetailFun("3");
            }
        }
        if(i == 5 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            Q_UNUSED(value);

        }
        if(i == 6 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            mCurrentWorkStatus.end = QString(temp_arr);
        }
        if(i == 7 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            Q_UNUSED(temp_arr);
        }
    }

    if(mCurrentWorkStatus.start.compare("0007")==0 &&\
            mCurrentWorkStatus.end.compare("000E")==0    )
    {
        ui->le_workstatus->setText("成型压力保压");
        mCurrentWorkStatus.workStatus = "成型压力保压";
    }
    else if(mCurrentWorkStatus.start.compare("0000")==0 &&\
            mCurrentWorkStatus.end.compare("0010")==0    )
    {
        ui->le_workstatus->setText("压机无动作");
        mCurrentWorkStatus.workStatus = "压机无动作";
    }
    else if(mCurrentWorkStatus.start.compare("0000")==0 &&\
            mCurrentWorkStatus.end.compare("000A")==0    )
    {
        ui->le_workstatus->setText("主缸快下");
        mCurrentWorkStatus.workStatus = "主缸快下";
    }

    else if(mCurrentWorkStatus.start.compare("0000")==0 &&\
            mCurrentWorkStatus.end.compare("0001")==0    )
    {
        ui->le_workstatus->setText("主缸慢下");
        mCurrentWorkStatus.workStatus = "主缸慢下";
    }

    else if(mCurrentWorkStatus.start.compare("0008")==0 &&\
            mCurrentWorkStatus.end.compare("000B")==0    )
    {
        ui->le_workstatus->setText("泄压");
        mCurrentWorkStatus.workStatus = "泄压";
    }
    else if(mCurrentWorkStatus.start.compare("0000")==0 &&\
            mCurrentWorkStatus.end.compare("0003")==0    )
    {
        ui->le_workstatus->setText("主缸快回");
        mCurrentWorkStatus.workStatus = "主缸快回";
    }
    if(m_post_once_flag)
    {
        putDetailFun("1");
    }
    ui->le_settime->setText(mCurrentWorkStatus.currSetValue);
    ui->le_realtime->setText(mCurrentWorkStatus.currRealvalue);
}

void PlasticPresses::parseObjCount(QString warnstring)
{
    QByteArray warnarr = QByteArray::fromHex(warnstring.toLatin1());
    QByteArray arr_info = warnarr.remove(0,1).remove(warnarr.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            mCurrentWorkStatus.objCount = QString::number(value);
            if(m_post_once_flag)
            {
                putDetailFun("4");
            }

        }
        if(i == 1 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            Q_UNUSED(value);
        }
        ui->le_objCount->setText(mCurrentWorkStatus.objCount);
        ui->le_obj_preCount->setText("0");

    }
}

void PlasticPresses::parseProcessSelectionStatus(QString processStr)
{
    QByteArray processArray = QByteArray::fromHex(processStr.toLatin1());
    QByteArray arr_info = processArray.remove(0,1).remove(processArray.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            QString processinfo = QString("%1").arg(value,9,2);//获取工艺选择参数的二进制序列;9 is the fieldWidth
            emit sendProcessInfo(processinfo);
        }

    }
}

void PlasticPresses::parseInputStatus(QString inputstatus)
{
    QByteArray inputStatusArray = QByteArray::fromHex(inputstatus.toLatin1());
    QByteArray arr_info = inputStatusArray.remove(0,1).remove(inputStatusArray.length()-3,3);
    QStringList list;
    list.clear();
    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            QString inputStatsinfo = QString("%1").arg(value,13,2);//获取工艺选择参数的二进制序列
            emit sendInputStatusInfo(inputStatsinfo);
        }

    }
}

void PlasticPresses::parseOutputStatus(QString outputstatus)
{
    QByteArray outputStatusArray = QByteArray::fromHex(outputstatus.toLatin1());
    QByteArray arr_info = outputStatusArray.remove(0,1).remove(outputStatusArray.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            QString outputStatsinfo = QString("%1").arg(value,0,2);//获取工艺选择参数的二进制序列
            emit sendOutputStatusInfo(outputStatsinfo);
        }

    }
}

void PlasticPresses::parseDelay1Data1(QString delay1Str)
{
    QByteArray delay1Array = QByteArray::fromHex(delay1Str.toLatin1());
    QByteArray arr_info = delay1Array.remove(0,1).remove(delay1Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16); //TODO 20180717 change
            m_DelayTimeSet1Para.LowPressureCount = QString::number(value);
        }

    }
}

void PlasticPresses::parseDelay1Data2(QString delay1Str)
{
    QByteArray delay1Array = QByteArray::fromHex(delay1Str.toLatin1());
    QByteArray arr_info = delay1Array.remove(0,1).remove(delay1Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            m_DelayTimeSet1Para.HighPressureCount = QString::number(value);
        }

    }
}

void PlasticPresses::parseDelay1Data3(QString delay1Str)
{
    QByteArray delay1Array = QByteArray::fromHex(delay1Str.toLatin1());
    QByteArray arr_info = delay1Array.remove(0,1).remove(delay1Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);
            m_DelayTimeSet1Para.LowProtectTime = QString::number(value/10);
        }

    }
}

void PlasticPresses::parseDelay1Data4(QString delay1Str)
{
    QByteArray delay1Array = QByteArray::fromHex(delay1Str.toLatin1());
    QByteArray arr_info = delay1Array.remove(0,1).remove(delay1Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);//TODO 20180719 Change above to this
            m_DelayTimeSet1Para.PressureReliefDelayTime = QString::number(value/10);
        }

    }
}

void PlasticPresses::parseDelay1Data5(QString delay1Str)
{
    QByteArray delay1Array = QByteArray::fromHex(delay1Str.toLatin1());
    QByteArray arr_info = delay1Array.remove(0,1).remove(delay1Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);
            m_DelayTimeSet1Para.LowPressureDelayTime = QString::number(value/10);
        }
    }
}

void PlasticPresses::parseDelay1Data6(QString delay1Str)
{
    QByteArray delay1Array = QByteArray::fromHex(delay1Str.toLatin1());
    QByteArray arr_info = delay1Array.remove(0,1).remove(delay1Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);//TODO 20180719 Change above to this
            m_DelayTimeSet1Para.HighProtectDelayTime = QString::number(value/10);
        }
    }
}

void PlasticPresses::parseDelay2Data1(QString delay2Str)
{
    QByteArray delay2Array = QByteArray::fromHex(delay2Str.toLatin1());
    QByteArray arr_info = delay2Array.remove(0,1).remove(delay2Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);//TODO 20180719 Change above to this
            m_DelayTimeSet2Para.PressureReliefDelayTime2 = QString::number(value/10);
        }
    }
}

void PlasticPresses::parseDelay2Data2(QString delay2Str)
{
    QByteArray delay2Array = QByteArray::fromHex(delay2Str.toLatin1());
    QByteArray arr_info = delay2Array.remove(0,1).remove(delay2Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);//TODO 20180719 Change above to this
            m_DelayTimeSet2Para.HighPaiQiDelayTime = QString::number(value/10);
        }
    }
}

void PlasticPresses::parseDelay2Data3(QString delay2Str)
{
    QByteArray delay2Array = QByteArray::fromHex(delay2Str.toLatin1());
    QByteArray arr_info = delay2Array.remove(0,1).remove(delay2Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            m_DelayTimeSet2Para.ChengxingBaoyaDelayTime = QString::number(value);
        }
        if(i == 5 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);
            m_DelayTimeSet2Para.PressureReliefDelayTime = QString::number(value/10);
        }
    }
}

void PlasticPresses::parseDelay2Data4(QString delay2Str)
{
    QByteArray delay2Array = QByteArray::fromHex(delay2Str.toLatin1());
    QByteArray arr_info = delay2Array.remove(0,1).remove(delay2Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            float  value = temp_arr.toFloat(nullptr);//TODO 20180719 Change above to this
            m_DelayTimeSet2Para.DingchuDelayTime = QString::number(value/10);
        }
    }
}

void PlasticPresses::parseDelay2Data5(QString delay2Str)
{
    QByteArray delay2Array = QByteArray::fromHex(delay2Str.toLatin1());
    QByteArray arr_info = delay2Array.remove(0,1).remove(delay2Array.length()-3,3);
    QStringList list;
    list.clear();

    for(int i=0;i<arr_info.length(); i+=4){
        QByteArray temparr = arr_info.mid(i,4);
        list.append(temparr);

    }
    for(int i = 0; i < list.size(); i++)
    {
        if(i == 0 )
        {
            QString str =  list.at(i);
            QByteArray array = str.toLatin1();
            QByteArray temp_arr = array.mid(2,2).append(array.mid(0,2));
            qint64  value = temp_arr.toInt(Q_NULLPTR,16);
            m_DelayTimeSet2Para.HandshakeSignal = QString::number(value);
        }
    }
}

void PlasticPresses::receiveHttpClientData(QByteArray str1, QByteArray str2)
{
    Q_UNUSED(str2);
    mHttpServer->response(str1);
    QJsonParseError jsonErr;
    QJsonDocument myjsonDoc1 = QJsonDocument::fromJson(str1,&jsonErr);
    if(jsonErr.error == QJsonParseError::NoError)
    {
        if(!myjsonDoc1.isEmpty())
        {
            if(myjsonDoc1.isObject())
            {
                QJsonObject jobj = myjsonDoc1.object();
                QJsonObject::iterator it = jobj.begin();

                saveProductionVariant(jobj,tProctionInfo);

                ProductionVariant productinfo;
                QString order_flag;
                queryCurrentOrder(productinfo,order_flag);
                if (!productinfo.TaskId.isEmpty())
                {
                    m_deviceState->setOrderState("已接单");
                }
                if (!productinfo.TaskId.isEmpty() && !productinfo.ProductName.isEmpty() && !productinfo.WorkNum.isEmpty())
                {
                    qDebug() << Q_FUNC_INFO << "Product Order is not Empty";
                    showProductionOrder();
                }

                while (it != jobj.end()) {
                    switch (it.value().type()) {
                    case QJsonValue::String:
                    {
                        QString startcmd = it.value().toString();
                        qDebug() << Q_FUNC_INFO <<startcmd<<jobj.value("Device_Type").toString()
                                 <<jobj.value("Device_Id").toString()
                                <<jobj.value("Production_Num").toString()
                               <<jobj.value("Batch_Num").toString()
                              <<jobj.value("Target_Weight").toString();
                    }
                        break;
                    default:
                        break;
                    }
                    it++;
                }
            }
        }
    }
}

void PlasticPresses::receiveplcConnnectedStatus(bool plcStatus)
{
    m_plcStatus = plcStatus;
}

void PlasticPresses::httpRegister_slots(bool status)
{
    if(status)
    {
        m_systemStatus &= 0xdfff;
    }
    else
    {
        m_systemStatus |= 0x2000;
        qDebug() << "~~~~~~NNNNNNNN~~~~~~~~~~~~~:"<<m_systemStatus;
    }
    if(status && !m_register_flag)
    {
        m_register_flag = true;
        m_httpClient->registerDeviceInfo( m_deviceInfo->deviceType,m_deviceInfo->deviceId,"register",QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"));
    }
}

void PlasticPresses::receiveHttpRegisterOK(bool registerOK)
{
    if(registerOK)
    {
        m_httpClient->posDeviceInfo(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"CurrentCount",mCurrentWorkStatus.objCount);
    }
}

void PlasticPresses::receiveProductionVariant_Main(ProductionVariant info)
{
    Q_UNUSED(info);
}

void PlasticPresses::posDetailFun(QString sequence)
{
    if(sequence.isEmpty())
    {
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"当前工作状态",mCurrentWorkStatus.workStatus);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"当前设定值",mCurrentWorkStatus.currSetValue);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"当前实际值",mCurrentWorkStatus.currRealvalue);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"工件计数",mCurrentWorkStatus.objCount);
        m_httpClient->posDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量",mCurrentWorkStatus.dumpEnergy);
    }
}

void PlasticPresses::putDetailFun(QString sequence)
{
    switch (sequence.toInt()) {
    case 1:
    {
        if(m_currentWorkStatus_temp.compare(mCurrentWorkStatus.workStatus)!=0)
        {
            m_currentWorkStatus_temp = mCurrentWorkStatus.workStatus;
            m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"当前工作状态",mCurrentWorkStatus.workStatus);
        }
    }
        break;
    case 2:
    {
        if(m_currentSetValue_temp.compare(mCurrentWorkStatus.currSetValue)!=0)
        {
            m_currentSetValue_temp = mCurrentWorkStatus.currSetValue;
            m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"当前设定值",mCurrentWorkStatus.currSetValue);
        }
    }
        break;
    case 3:
    {
        if(m_currentRealValue_temp.compare(mCurrentWorkStatus.currSetValue)!=0)
        {
            m_currentRealValue_temp = mCurrentWorkStatus.currRealvalue;
            m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"当前实际值",mCurrentWorkStatus.currRealvalue);
        }
    }
        break;
    case 4:
    {
        if(m_currentCount_temp.compare(mCurrentWorkStatus.objCount)!=0)
        {
            m_currentCount_temp = mCurrentWorkStatus.objCount;
            m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"工件计数",mCurrentWorkStatus.objCount);
        }
    }
    case 5:
    {
        if(m_dumpEnergy_temp.compare(mCurrentWorkStatus.dumpEnergy)!=0)
        {
            m_dumpEnergy_temp = mCurrentWorkStatus.dumpEnergy;
            m_httpClient->putDeviceDetail(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"耗电量",mCurrentWorkStatus.dumpEnergy);
        }
    }
        break;
    default:
        break;
    }
}

void PlasticPresses::initFlash()
{
    setFlash(ui->lab_warn);
}

void PlasticPresses::initMitsubishiPlcFun()
{
    m_mitsubishi = new MitsubishiWnd("/dev/" + m_usbPortName.port2_name,"9600","7","even","1");
    connect(m_mitsubishi,   SIGNAL(workStatus(QString)),                                this,           SLOT(parseWorkStatus(QString)));
    connect(m_mitsubishi,   SIGNAL(objCount(QString)),                                  this,           SLOT(parseObjCount(QString)));
    connect(m_mitsubishi,   SIGNAL(sendProcessSelectionRawData(QString)),               this,           SLOT(parseProcessSelectionStatus(QString)));
    connect(m_mitsubishi,   SIGNAL(sendInputStatusRawData(QString)),                    this,           SLOT(parseInputStatus(QString)));
    connect(m_mitsubishi,   SIGNAL(sendOutputStatusRawData(QString)),                   this,           SLOT(parseOutputStatus(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay1RawData1(QString)),                        this,           SLOT(parseDelay1Data1(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay1RawData2(QString)),                        this,           SLOT(parseDelay1Data2(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay1RawData3(QString)),                        this,           SLOT(parseDelay1Data3(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay1RawData4(QString)),                        this,           SLOT(parseDelay1Data4(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay1RawData5(QString)),                        this,           SLOT(parseDelay1Data5(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay1RawData6(QString)),                        this,           SLOT(parseDelay1Data6(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay2RawData1(QString)),                        this,           SLOT(parseDelay2Data1(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay2RawData2(QString)),                        this,           SLOT(parseDelay2Data2(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay2RawData3(QString)),                        this,           SLOT(parseDelay2Data3(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay2RawData4(QString)),                        this,           SLOT(parseDelay2Data4(QString)));
    connect(m_mitsubishi,   SIGNAL(sendDelay2RawData5(QString)),                        this,           SLOT(parseDelay2Data5(QString)));
    connect(m_mitsubishi,   SIGNAL(plcConnectStatus(bool)),                             this,           SLOT(receiveplcConnnectedStatus(bool)));
    connect(this,           SIGNAL(writeLowPressFlag(bool)),                            m_mitsubishi,   SLOT(writeLowpressStatus(bool)));
    connect(this,           SIGNAL(writeAftercompactionFlag(bool)),                     m_mitsubishi,   SLOT(writeAftercompactionStatus(bool)));
    connect(this,           SIGNAL(writeChouXinGangFlag(bool)),                     m_mitsubishi,   SLOT(writeChouXinGangStatus(bool)));
    connect(this,           SIGNAL(writeMotorModeFlag(bool)),                     m_mitsubishi,   SLOT(writeMotorStatus(bool)));
    connect(this,           SIGNAL(writeGaoYaPaiQiFlag(bool)),                     m_mitsubishi,   SLOT(writeGaoYaPaiQiStatus(bool)));

    connect(this,           SIGNAL(writeLowPressureCount(QString,QString)),             m_mitsubishi,   SLOT(writeLowPressureCount(QString,QString)));
    connect(this,           SIGNAL(writeHighPressureCount(QString,QString)),            m_mitsubishi,   SLOT(writeHighPressureCount(QString,QString)));
    connect(this,           SIGNAL(writeLowProtectDelaytime(QString,QString)),          m_mitsubishi,   SLOT(writeLowProtectDelaytime(QString,QString)));
    connect(this,           SIGNAL(writeReliefPressureDelaytime(QString,QString)),      m_mitsubishi,   SLOT(writeReliefPressureDelaytime(QString,QString)));
    connect(this,           SIGNAL(writeLowPressurePaiqiDelaytime(QString,QString)),    m_mitsubishi,   SLOT(writeLowPressurePaiqiDelaytime(QString,QString)));
    connect(this,           SIGNAL(writeHighPressureBaoyaDelaytime(QString,QString)),   m_mitsubishi,   SLOT(writeHighPressureBaoyaDelaytime(QString,QString)));
    connect(this,           SIGNAL(writeReliefPressureDelaytime2_2(QString,QString)),   m_mitsubishi,   SLOT(writeReliefPressureDelaytime2_2(QString,QString)));
    connect(this,           SIGNAL(writeHighPressurePaiqiDelaytime_2(QString,QString)), m_mitsubishi,   SLOT(writeHighPressurePaiqiDelaytime_2(QString,QString)));
    connect(this,           SIGNAL(writeMoldingBaoyaDelaytime_2(QString,QString)),      m_mitsubishi,   SLOT(writeMoldingBaoyaDelaytime_2(QString,QString)));
    connect(this,           SIGNAL(writeTopoutDelaytime_2(QString,QString)),            m_mitsubishi,   SLOT(writeTopoutDelaytime_2(QString,QString)));
    connect(this,           SIGNAL(writeReliefPressureDelaytime_2(QString,QString)),    m_mitsubishi,   SLOT(writeReliefPressureDelaytime_2(QString,QString)));
    connect(this,           SIGNAL(sendCurrentWgtIndex(WgtChanged)),                    m_mitsubishi,   SLOT(getTransforWgt(WgtChanged)));//TODO20180323
    connect(this,           SIGNAL(writeClearCountCmd()),    m_mitsubishi,   SLOT(writeClearCount()));
}

void PlasticPresses::deleteFun()
{
    if(m_mitsubishi)
    {
        delete m_mitsubishi;
    }
    if(m_httpClient)
    {
        delete m_httpClient;
    }
    if(mHttpServer)
    {
        delete mHttpServer;
    }
    if(m_mainmenu)
    {
        delete m_mainmenu;
    }
    if(m_ContactUsSet)
    {
        delete m_ContactUsSet;
    }
    if(m_LogonRightsEdit)
    {
        delete m_LogonRightsEdit;
    }
    if(m_PlasticPressessInfo)
    {
        delete m_PlasticPressessInfo;
    }
    if(m_ammeterDate)
    {
        delete m_ammeterDate;
    }
    if(m_circleTimer)
    {
        delete m_circleTimer;
    }
    if(mEd)
    {
        delete mEd;
    }
    delete ui;
}

QJsonObject PlasticPresses::getDatas()
{
    if( false == _DatasObj.keys().contains("模2温度") )
        _DatasObj["模2温度"] = QString("0");
    if( false == _DatasObj.keys().contains("模1温度") )
        _DatasObj["模1温度"] =QString("0");
    if( false == _DatasObj.keys().contains("成型保压延时") )
        _DatasObj["成型保压延时"] = QString("0");
    if( false == _DatasObj.keys().contains("泄压延时2时间") )
        _DatasObj["泄压延时2时间"] = QString("0");
    if( false == _DatasObj.keys().contains("高压排气延时") )
        _DatasObj["高压排气延时"] = QString("0");
    if( false == _DatasObj.keys().contains("顶出延时时间") )
        _DatasObj["顶出延时时间"] = QString("0");
    if( false == _DatasObj.keys().contains("高压保压延时") )
        _DatasObj["高压保压延时"] = QString("0");
    if( false == _DatasObj.keys().contains("低压排气次数") )
        _DatasObj["低压排气次数"] = QString("0");
    if( false == _DatasObj.keys().contains("泄压延时时间") )
        _DatasObj["泄压延时时间"] = QString("0");
    if( false == _DatasObj.keys().contains("握手信号") )
        _DatasObj["握手信号"] = QString("0");
    if( false == _DatasObj.keys().contains("低压排气延时") )
        _DatasObj["低压排气延时"] = QString("0");
    if( false == _DatasObj.keys().contains("泄压延时") )
        _DatasObj["泄压延时"] = QString("0");
    if( false == _DatasObj.keys().contains("耗电量") )
        _DatasObj["耗电量"] = QString("0");
    if( false == _DatasObj.keys().contains("高压排气次数") )
        _DatasObj["高压排气次数"] = QString("0");
    if( false == _DatasObj.keys().contains("低压保压延时") )
        _DatasObj["低压保压延时"] = QString("0");
    return _DatasObj;
}

void PlasticPresses::sendUpdateTodayTask()
{
    QString status;
    if( ui->le_workNum->text().toInt() == 0 )
        status = "待机";
    else if( ui->le_objCount->text().toInt() >= 0 && (ui->le_objCount->text().toInt()* mParent->_productionVariant.ToolingRatio.toInt())< ui->le_workNum->text().toInt() )
        status = "生产中";
    else
        status = "已完成";

    QJsonObject obj;
    obj["productname"] = ui->le_productName->text();
    obj["productcode"] = mParent->_productionVariant.ProductCode;
    obj["taskstatus"] = status;
    obj["taskyield"] = "0";
    if(ui->le_objCount->text().toInt() > 0 )
        obj["TotalProductCount"] = ui->le_objCount->text().toInt();   //obj["FinishedProduct"] = ui->le_objCount->text();
    else
        obj["TotalProductCount"] = QString("0").toInt();    //obj["FinishedProduct"] = QString("0");
    obj["Energy"] = _DatasObj["耗电量"].toString();
    obj["productcount"] = ui->le_workNum->text();
    obj["starttime"] = startTime;
    obj["offtime"] = endTime;
    m_httpClient->posTodayTask(m_deviceInfo->deviceType,
                               m_deviceInfo->deviceId,
                               mParent->_productionVariant.TaskId,
                               "task",
                               obj,
                               2);
}

void PlasticPresses::setFlash(QWidget *ed)
{
    if(mEd!=NULL)
        showEditorText();
    if(mEd!=ed)
    {
        mEd = ed;
        if(mEd!=0)
        {
            mCurrStr = text();
            showEditorText();
        }
    }
    if(mEd!=NULL)
    {
        mBackColor = mEd->palette().color(QPalette::Window);
        mTextColor = mEd->palette().color(QPalette::Text);

    }
}

void PlasticPresses::showEditorText()
{
    if(mEd->inherits("QLabel"))
    {
        QPalette pal    = mEd->palette();
        pal.setColor(QPalette::WindowText,mTextColor);
        mEd->setPalette(pal);
    }
    else if(mEd->inherits("QLineEdit"))
    {
        QPalette pal    = mEd->palette();
        pal.setColor(QPalette::Text,mTextColor);
        mEd->setPalette(pal);
    }
}

void PlasticPresses::hideEditorText()
{

    if(mEd->inherits("QLabel"))
    {
        QPalette pal    = mEd->palette();
        pal.setColor(QPalette::WindowText,mBackColor);
        mEd->setPalette(pal);

    }
    else if(mEd->inherits("QLineEdit"))
    {
        QPalette pal    = mEd->palette();
        pal.setColor(QPalette::Text,mBackColor);
        mEd->setPalette(pal);
    }

}
void PlasticPresses::deviceCircleTimeSlot()
{
    if(!m_post_once_flag)
    {
        posDetailFun("");
        m_post_once_flag = true;
    }
}

void PlasticPresses::timerEvent(QTimerEvent *event)
{
    int t = event->timerId();
    if(t == timeId)
    {
        ui->lab_date->setText(QDate::currentDate().toString("yyyy-MM-dd"));
        ui->lab_time->setText(QTime::currentTime().toString("hh:mm:ss"));
        showFlashLabel();
    }
    if(t == heartId)
    {
        m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"heartbeat","on-line-again");
    }
    if(t == timeDelayId)
    {
        if(m_plcStatus)
        {
            emit plcConnnectedStatus_signals(true);
        }
        else
        {
            emit plcConnnectedStatus_signals(false);
        }

        if(mWgtChanged == DELAYTIME_SETTING1_WGT)
            emit sendDelay1Info(m_DelayTimeSet1Para);
        else if(mWgtChanged == DELAYTIME_SETTING2_WGT)
            emit sendDelay2Info(m_DelayTimeSet2Para);
        emit sendProductionVariant(tProctionInfo);
    }
    if (t == m_task_timeId)
    {
        if ( !m_orderFinish_flag )
        {

            if(  mParent->_productionVariant.ToolingRatio.toInt() == 1
                 && ui->le_objCount->text().toInt() >= ui->le_workNum->text().toInt() && ui->le_workNum->text().toInt() > 0)
            {
                endTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
                m_orderFinish_flag = true;

                sendUpdateTodayTask();
                send7Datas();
                while(_workArr_pla.isEmpty() == false)
                    _workArr_pla.removeFirst();

                QString tips = tr("此订单数量已完成，请输入不良品数！");
                if( _msgDlg == NULL )
                    _msgDlg = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
                _msgDlg->hideCancelBtn();
                _msgDlg->show();
                connect(_msgDlg, &QDialog::accepted, [=](){
                    ui->le_defectiveNumber->setFocus();
                    QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
                                      Qt::NoButton, Qt::NoButton, Qt::NoModifier);
                    QApplication::sendEvent(ui->le_defectiveNumber, &event);
                    _msgDlg->deleteLater();
                } );
                ui->le_defectiveNumber->installEventFilter(this);
                ui->btn_orderCompleted->setEnabled(true);
                _orderBegin = false;
                QC_Scan_ckeck = false;
            }
            else if( (ui->le_objCount->text().toInt()* mParent->_productionVariant.ToolingRatio.toInt())>= ui->le_workNum->text().toInt()
                     && ui->le_workNum->text().toInt() > 0 )
            {
                endTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
                m_orderFinish_flag = true;

                sendUpdateTodayTask();
                send7Datas();
                while(_workArr_pla.isEmpty() == false)
                    _workArr_pla.removeFirst();

                QString tips = tr("此订单数量已完成，请输入不良品数！");
                //MyMessageDialog *dialog = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));
                _msgDlg = new MyMessageDialog(tips,tr("提示!"),this,tr("否"),tr("确定"));

                _msgDlg->hideCancelBtn();
                _msgDlg->show();
                connect(_msgDlg, &QDialog::accepted, [=](){
                    ui->le_defectiveNumber->setFocus();
                    QMouseEvent event(QEvent::MouseButtonPress, QPoint(),
                                      Qt::NoButton, Qt::NoButton, Qt::NoModifier);
                    QApplication::sendEvent(ui->le_defectiveNumber, &event);
                    _msgDlg->deleteLater();
                } );

                ui->le_defectiveNumber->installEventFilter(this);
                ui->btn_orderCompleted->setEnabled(true);
                _orderBegin = false;
                QC_Scan_ckeck = false;
            }
        }
    }
}

void PlasticPresses::slot_clearOrderMsg()
{
    ui->le_workNum->clear();
    ui->le_workTime->clear();
    ui->le_productName->clear();
    ui->lbl_orderNumber->clear();
    ui->le_objCount->clear();
    sendNotGood();
}

void PlasticPresses::setOrderButtonDisabled()
{
    //TODO Need finish
    ui->btn_orderCompleted->setEnabled(false);
}

void PlasticPresses::clearPressingCount()
{
    //do noting, need son class to do 2018 11/18 xuyifu
    emit writeClearCountCmd();
    //ui->le_objCount->setText("0");
}

void PlasticPresses::setDefectValue()
{
    //TODO need finish
    ui->le_defectiveNumber->setText("0");
}

void PlasticPresses::showFlashLabel()
{
    if(mFlasbEnable)
    {
        if(mEd)
        {
            if(isVisible())
            {
                mFlash++;
                if(mFlash<2)
                {
                    hideEditorText();
                }
                else if(mFlash<4)
                {
                    showEditorText();
                }
                else if(mFlash>6)
                {
                    mFlash = 0;
                }
            }
            else
            {
                showEditorText();
            }
        }
    }
}

QString PlasticPresses::text()
{

    if(mEd)
    {
        if(mEd->inherits("QLineEdit"))
        {
            return ((QLineEdit*)mEd)->text();
        }
        else if(mEd->inherits("QLabel"))
        {
            return ((QLabel*)mEd)->text();
        }
    }
    else
    {
        return mCurrStr;
    }
    return mCurrStr;
}

void PlasticPresses::initHttpClient()
{
    connect(m_httpClient,   SIGNAL(startHttpWork()),        this,   SLOT(deviceCircleSend()));
    connect(m_httpClient,   SIGNAL(startHttpWork()),        this,   SLOT(updateCurrentCount()));
    connect(m_httpClient,   SIGNAL(ipStatusSignals(bool)),  this,   SLOT(receiveipStatus_slots(bool)));
    connect(m_httpClient,   SIGNAL(ipStatusSignals(bool)),  this,   SLOT(httpRegister_slots(bool)));
    connect(m_httpClient,   SIGNAL(registerOK(bool)),       this,   SLOT(receiveHttpRegisterOK(bool)));
    connect(m_httpClient,   SIGNAL(sendUserPerssion(QString)),      this,   SLOT(receiveHttpUserPermission(QString)));//TODO 20180710
    connect(m_httpClient,   SIGNAL(sendStation_OfHttp(QString)),    this,   SLOT(receiveStation_fromHttp(QString)));
    connect(m_httpClient,   SIGNAL(orderConfirmOK()),               this,   SLOT(showOrderCheckOK_Tips()));
    connect(m_httpClient,   SIGNAL(updateDeviceState_Signals()),    this,   SLOT(updateDeviceState_Slots()));
}

void PlasticPresses::initHttpServer()
{
    mHttpServer = new HttpServer(this);
    mHttpServer->listen(QHostAddress::Any,4000);
    connect(mHttpServer,SIGNAL(dataSend(QByteArray,QByteArray)),this,SLOT(receiveHttpClientData(QByteArray,QByteArray)));
}

void PlasticPresses::initSocketTest()
{
    m_tcpSocket = new TcpSocket();
    QObject::connect(m_tcpSocket,SIGNAL(onConnected()),this,SLOT(writeDataToTcpServer()));
}

void PlasticPresses::removeDefectNumEvent()
{
    ui->le_defectiveNumber->removeEventFilter(this);
}

void PlasticPresses::setOrderButtonShow()
{
    //TODO need finish
}

void PlasticPresses::setOrderButtonHidden()
{
    //TODO need finish
}

void PlasticPresses::deleteSpotScrollText()
{
    //TODO NEED
}

void PlasticPresses::startSpotCheckTimer()
{
    //TODO Need
}

void PlasticPresses::setCurrentOrderStatusShow(ProductionVariant &productInfo)
{
    Q_UNUSED(productInfo);
    ui->le_productName->setText(productInfo.ProductName);
    ui->le_workNum->setText(productInfo.WorkNum);
    ui->le_workTime->setText(productInfo.OrderStartTime);
    ui->lbl_orderNumber->setText(productInfo.TaskId);
    m_current_taskId = productInfo.TaskId;
}

void PlasticPresses::sendCloseInputDialogSignal_ByHeadMan()
{
    emit closeInputDialog_ByHeadMan();
}

void PlasticPresses::sendCloseConfirmDialogSignal_ByQcMan()
{
    emit closeSenconConfirmDialog_ByQcMan();
}

void PlasticPresses::enableButton(bool)
{
    //TODO Maybe not need
}

void PlasticPresses::initScaleSerialSetting()
{
    QString portName = m_usbPortName.port0_name;   //获取串口名

    qDebug() << Q_FUNC_INFO << "port name:" << m_usbPortName.port0_name;

#ifdef Q_OS_LINUX
    m_scaleCom = new QextSerialPort("/dev/" + portName);
#elif defined (Q_OS_WIN)
    if(m_scaleCom == NULL)
    {
        m_scaleCom = new QextSerialPort(portName);
    }
#endif
    connect(m_scaleCom, SIGNAL(readyRead()), this, SLOT(readScaleCom()));
    //设置波特率
    m_scaleCom->setBaudRate((BaudRateType)9600);
    //设置数据流控制
    m_scaleCom->setFlowControl(FLOW_OFF);
    //设置延时
    m_scaleCom->setTimeout(200);//TODO change 50 to 100
    if(!m_scaleCom->isOpen()) {
        m_scaleCom->open(QIODevice::ReadWrite);
    }
    //设置数据位
    m_scaleCom->setDataBits((DataBitsType)8);
    //设置校验
    m_scaleCom->setParity(PAR_NONE);
    m_scaleCom->setStopBits(STOP_1);
}

void PlasticPresses::saveElectrodeCountToDataBase()
{
    //TODO 20180806 Maybe not need
}

bool PlasticPresses::eventFilter(QObject *watched, QEvent *event)
{
    if(event->type() == QEvent::MouseButtonPress)
    {
        if(watched == ui->le_defectiveNumber)
        {
            inputDefectiveNum();//输入焊接不良品数
        }
    }
    return QWidget::eventFilter(watched,event);

}

void PlasticPresses::inputDefectiveNum()
{
    ui->le_defectiveNumber->clearFocus();
    QWidget *back = new QWidget(this);
    back->setGeometry(0,0,SCREEN_WIDTH,SCREEN_HIGH);
    back->setWindowFlags(Qt::FramelessWindowHint|Qt::WindowStaysOnTopHint); //Windows上设为透明色 需有Qt::FramelessWindowHint
    back->setAttribute(Qt::WA_TranslucentBackground,true); //Windows上设为透明色
    back->setWindowModality(Qt::WindowModal);
    back->show();
    inputDialog *inputdialog = new inputDialog(back,"请输入不良品",false,5,0,0,true);
    inputdialog->setWindowModality(Qt::WindowModal);
    inputdialog->hideSome();
    inputdialog->show();
    connect(inputdialog,SIGNAL(inputValue(int)),this,SLOT(acceptDefectiveValue(int)));
    connect(inputdialog,SIGNAL(exitInputdialog()),back,SLOT(deleteLater()));
    connect(inputdialog,SIGNAL(exitInputdialog()),inputdialog,SLOT(deleteLater()));
}

void PlasticPresses::showDefectiveNumTips()
{
    defectiveNumTipsCheckOK();
    m_deviceState->setDeviceStation(DeviceState::FIRST_CHECK_STATION);
}

void PlasticPresses::acceptDefectiveValue(int val)
{
    if( val >  ui->le_workNum->text().toInt())
    {
        MyMessageDialog::message(0,"警告！"," 不良品数量大于订单数！",2000);
        return;
    }
    _badNum = val;
    ui->le_defectiveNumber->setText(QString::number(_badNum));
    showDefectiveNumTips();
}

void PlasticPresses::escFromSettings()
{

}



void PlasticPresses::readScaleCom()
{
    if (m_scaleCom->canReadLine() ) {

        QString temp = m_scaleCom->readAll();

        if (temp.contains("pcs"))
        {
            qDebug() << "\n\n pcs:" << temp;
            QString count = temp.remove("pcs");
            emit sendScaleCount(count);
            //"     10pcs\n"
        }

        if (temp.contains("ST") )
        {
            if (temp.startsWith("\r\r")) {
                temp = temp.remove(0,1);
                //"\rST,GS    0.70kg\r    35.1217 g\n
            }
            QString scaleWeight;
            scaleWeight = temp.mid(6,8);
            emit sendScaleWeight(scaleWeight);
            //"\r\rST,GS    0.46kg\r    46.1190 g\n"
        }
    }
}

void PlasticPresses::updateDeviceState_Slots()
{
    ProductionVariant productinfo;
    queryCurrentOrder(productinfo,getCurrentTaskId());
    m_deviceState->setMachineState(DeviceState::MACHINE_WORKING);//string value is : processing
    QString deviceState;
    m_deviceState->getMachineStateString(deviceState);
    m_httpClient->putUpdateDevice(m_deviceInfo->deviceType,m_deviceInfo->deviceId,"State",deviceState);
    /*--- POST订单状态 ----*/
    m_httpClient->postOrderState(m_deviceState->getOrderState(),m_deviceInfo->deviceType,m_deviceInfo->deviceId,productinfo.TaskId);
}

void PlasticPresses::on_settingBtn_clicked()
{
    emit openSettingSignal();
}

void PlasticPresses::on_btn_clearCount_clicked()
{
    emit writeClearCountCmd();
}


/*----zhanglong*/
void PlasticPresses::LEDFrashCircleTimeSlot()
{
    /*status show*/
    /*Add Alarm text----zhanglong*/
    QStringList list;
    if(l_Equipment_ckeck != Equipment_ckeck)
    {
        if(Equipment_ckeck)
        {
            list << tr("请设备维护人员对设备进行点检！");
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            list.clear();
        }
        l_Equipment_ckeck = Equipment_ckeck;
    }

    if (l_QC_Scan_ckeck != QC_Scan_ckeck)
    {
        if(QC_Scan_ckeck)
        {
            list << tr("请QC人员进行巡检！");
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            if (!l_Equipment_ckeck){
                list.clear();
            }
        }
        l_QC_Scan_ckeck = QC_Scan_ckeck;
    }
    if(l_systemStatus != m_systemStatus)
    {
        /*LED Fresh*/
        if(m_systemStatus & 0x000f)
        {
            qDebug() << "+++++++++++++++ZZZZZZZZ:" <<m_systemStatus;
            m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","04 00",false);
        }
        else
        {
            if(m_systemStatus & 0xf000)
            {
                qDebug() << "-------------ZZZZZZZZ:" <<m_systemStatus;
                m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","02 00",false);
            }
            else
            {
                m_ammeterDate->writeCmd("02","0F","00","10","RTU","02","09 00",false);
            }
        }
        l_systemStatus = m_systemStatus;

        if(Equipment_ckeck)
        {
            list << tr("请设备维护人员对设备进行点检！");
            /*ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);*/
        }
        else
        {
            list.clear();
        }
        if(QC_Scan_ckeck)
        {
            list << tr("请QC人员进行巡检！");
            /*ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);*/
        }
        else
        {
            if (!l_Equipment_ckeck){
                list.clear();
            }
        }

        if(m_systemStatus)
        {
            if(m_systemStatus & 0x0001)
            {
                list.append(AlarmList.at(0));
            }
            if(m_systemStatus & 0x0002)
            {
                list.append(AlarmList.at(1));
            }
            if(m_systemStatus & 0x2000)
            {
                list.append(AlarmList.at(13));
            }
            if(m_systemStatus & 0x4000)
            {
                list.append(AlarmList.at(14));
            }
            if(m_systemStatus & 0x8000)
            {
                list.append(AlarmList.at(15));
            }
            ui->spotCheckScroll->show();
            ui->spotCheckScroll->startTimerId();
            ui->spotCheckScroll->setScrollText(list);
        }
        else
        {
            /*list.removeAll();*/
            if((!Equipment_ckeck) && (!QC_Scan_ckeck))
            {
                list.clear();
                ui->spotCheckScroll->hide();
            }
        }
        //list.append(AlarmList.at(2));
        //list = AlarmList.at(0)+AlarmList.at(2)+AlarmList.at(3)+AlarmList.at(4);
        if (!list.isEmpty()){
            for (int i=0;i<list.size();i++){
                QString str = list.at(i);
                if (str.trimmed()!=""){
                    postWarnData(str,QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"));
                }
            }
        }

    }
    qDebug() << "~~~~~~ZZZZZZZZ~~~~~~~~~~~~~~~~~~~~:" <<l_systemStatus<<m_systemStatus;

}

void PlasticPresses::on_le_objCount_textChanged( QString str)
{
//    if( mParent->_productionVariant.ToolingRatio.toInt() == 1 )
//    {
//        if( ui-> le_objCount->text().toInt() > ui->le_workNum->text().toInt())
//        {
//            _msgDlg.accept();
//        }
//    }
//    else
//    {
//        if( (ui->le_objCount->text().toInt()* mParent->_productionVariant.ToolingRatio.toInt())
//                >  ui->le_workNum->text().toInt())
//        {
//            _msgDlg.accept();
//        }
//    }
    //ProductionVariant p = mParent->_productionVariant;
    if( str.toInt() <= 0) //如果为0则直接清空计数，上抛数据全部清空
    {
        _iNum = 0;  //计数清0
        while(_workArr_pla.isEmpty() == false)
            _workArr_pla.removeFirst();
        return;
    }

    _iNum++;
    if( _iNum < TIMES )
    {
        _workArr_pla.append( getDatas() );
        return ;
    }

    if( _iNum >= TIMES)
    {
        _workArr_pla.append( getDatas() );
        _iNum = 0;
        send7Datas(); //每30次只发7号数据
        while(_workArr_pla.isEmpty() == false)
            _workArr_pla.removeFirst();
        return;
    }
}

void PlasticPresses::send7Datas()
{
    m_httpClient->pos7Datas(m_deviceInfo->deviceType,
                            m_deviceInfo->deviceId,
                            mParent->_productionVariant.TaskId,
                            _workArr_pla  );
}

void PlasticPresses::on_pushButton_clicked()
{
    int current = ui->le_objCount->text().toInt() + 1;
    ui->le_objCount->setText( QString::number(current));
}

void PlasticPresses::sendNotGood()
{
    m_httpClient->posNotGood(m_deviceInfo->deviceType,
                             m_deviceInfo->deviceId,
                             mParent->_productionVariant.TaskId,
                             "task",
                             ui->le_defectiveNumber->text().toInt()
                             );
}
